package edu.asu.sefcom.extract.profile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import edu.asu.sefcom.extract.profile.data.Neo4jConnector;

public class CommProfileParserTemplate extends Parser implements
		ApplicationContextAware {

	Logger logger = Logger.getLogger(CommProfileParserTemplate.class);

	Neo4jConnector connector;

	ApplicationContext applicationContext;

	Map<String, List<String>> mapofusers = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	String postStart;

	String postEnd;

	@Override
	public void parseData(String fileName) throws IllegalArgumentException {
		String fileData = readFile(fileName);
		List<String> resultList = new ArrayList<String>();
		resultList.add(fileData);
		extractAttributes(resultList);
		resultList.clear();
	}

	private Map<String, PostData> extractAttributes(List<String> listPosts) {
		Map<String, PostData> returnMap = new HashMap<String, PostData>();
		String post1 = "";
		int count = 0;

		logger.debug("POSTS PRINT - " + listPosts);
		Map<String, Boolean> mapOfEmptyFields = new ConcurrentHashMap<String, Boolean>();
		Map<String, String> mapOfFields = null;
		for (String post : listPosts) {
			logger.info("POSTS # - " + ++count);
			mapOfFields = new ConcurrentHashMap<String, String>();

			List<String> users = null;
			List<String> dates=null;
			String[] arr5 = { "bhprofileparser1" };
			for (String beanName : arr5) {
				if (checkforexist(beanName)) {
					try {
						MultiFieldParser userExtractor = (MultiFieldParser) applicationContext
								.getBean(beanName);
						users = userExtractor.extractFields(post);
						logger.info("users - " + users);

						printOut("USERS", "users - ("
								+ userExtractor.getClass().getName() + ")",
								users.toString(), mapOfEmptyFields);
					} catch (Exception e) {
						System.out.println("UPT tag: " + e);
						e.printStackTrace();
					}
				}

				// ///////////
				String[] arr6 = { "bhprofiledateparser1" };
				
				for (String beanName2 : arr6) {
					if (checkforexist(beanName2)) {
						try {
							MultiFieldParser userExtractor = (MultiFieldParser) applicationContext
									.getBean(beanName2);
							dates = userExtractor.extractFields(post);

							printOut("startdate", "startdate - ("
									+ userExtractor.getClass().getName() + ")",
									dates.get(0).toString(), mapOfEmptyFields);
							printOut("enddate", "enddate - ("
									+ userExtractor.getClass().getName() + ")",
									dates.get(1), mapOfEmptyFields);
						} catch (Exception e) {
							System.out.println("UPT tag: " + e);
							e.printStackTrace();
						}
					}
				}
				// ///////////
			}
			storeData(dates,users, userName);
			mapOfFields.clear();
		}
		unique.clear();
		logger.info("------ISEMPTY-----------"
				+ mapOfEmptyFields.containsValue(false));
		logger.warn("------NONEMPTYFIELDS----" + mapOfEmptyFields);
		String msg = listPosts.size() > 0 ? "GOTCONTENT" : "";
		logger.info("--------------------" + msg
				+ "------------------------------------------");
		logger.debug(post1);

		return returnMap;
	}

//	public void storeFollowsData(String userName, List<String> follows) {
//
//		connector = (Neo4jConnector) this.applicationContext
//				.getBean("connector");
////		connector.storeUserFollowsRel(userName, follows);
//		
//	}

	public void storeData(List<String> dates, List<String> users,
			String commName) {
		connector = (Neo4jConnector) this.applicationContext
				.getBean("connector");
		if(users.size()==1){
			if(users.get(0) == ""){
				return;
			}
		}
		connector.storeCommData(dates,users, commName);
	}

//	public static void main(String[] args){
//		List<String> list = new ArrayList<String>(Arrays.asList(""));
//		System.out.println(list);
//		list.removeAll(Arrays.asList("", null));
//		System.out.println(list);
//	}
	
	private boolean checkforexist(String beanName) {
		boolean skip = true;
		if (skip) {
			return skip;
		} else {
			// logger.warn("beanname req: " + beanName);
			String user1 = userName;
			boolean result = false;
			try {
				if (null == mapofusers) {
					mapofusers = new HashMap<String, List<String>>();
					FileReader fileReader = new FileReader(new File(
							"src/edu/parse/profile/users-check.txt"));
					BufferedReader in = new BufferedReader(fileReader);
					String str;
					while ((str = in.readLine()) != null) {
						String userfile = str.split("=")[0];
						List<String> beansL = new ArrayList<String>();
						logger.debug("userfile " + userfile);
						String beanNames = str.split("=")[1];
						beansL = Arrays.asList(beanNames.split(","));
						logger.debug("beanL " + beansL);
						mapofusers.put(userfile, beansL);
					}
					in.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			for (String userfile : mapofusers.keySet()) {
				if (userfile.equalsIgnoreCase(user1)) {
					List<String> beansL = mapofusers.get(userfile);
					if (beansL.contains(beanName)) {
						result = true;
						// logger.warn("beanname found: " + beanName);
					}
				}
			}
			return result;
		}
	}


	public void updateMap(String key, String fieldToInput, String oldVal,
			Map<String, String> mapOfFields) {
		boolean res = fieldToInput.length() > oldVal.length() ? true : false;
		logger.warn("old val : " + oldVal);
		logger.warn("new val : " + fieldToInput);
		if (res) {
			mapOfFields.put(key, fieldToInput);
		}
	}

	Set<String> unique = new HashSet<String>();

	private void printOut(String key, String msg, String heading,
			Map<String, Boolean> mapOfEmptyFields) {
		heading = heading.replaceAll("&nbsp;", "");
		// if(unique.add(msg + heading)){
		// logger.warn(msg + heading);
		// }
		if (heading != "") {
			Object val = mapOfEmptyFields.get(key);
			if (null == val) {

				logger.warn(msg + heading);
			}
			if (null != val && !((Boolean) val)) {
				logger.warn(msg + heading);
			}

		}

	}
}
